/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EmployeeEducationEditor.java
 *
 * Created on Mar 27, 2010, 12:02:10 PM
 */

package org.foment.gem.beans;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.foment.joliage3.core.logging.Logger;
import org.foment.joliage3.sql.Database;
import static org.foment.joliage3.core.internationalization.Internationalization.i18n;
import static org.foment.joliage3.core.logging.Logger.log;
import org.foment.gem.Integrator;
import org.foment.data.User;

/**
 *
 * @author Dusan
 */
public class EmployeeEducationEditor extends javax.swing.JPanel implements User.UserListener {

    /** Creates new form EmployeeEducationEditor */
    public EmployeeEducationEditor()
    {
        
        initComponents();
        setComponents();

        Integrator._user.addListener(this);

        checkPrivileges();

        flg2_EmployeeEducationDepartment.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
                            public void insertUpdate(DocumentEvent e) { updated(e);}
                            public void removeUpdate(DocumentEvent e) { updated(e);}
                            public void changedUpdate(DocumentEvent e) { updated(e);}
                            public void updated(DocumentEvent e) {setDataModified(true);}
                            });


        flg2_EmployeeEducationFacultyTitle.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
                            public void insertUpdate(DocumentEvent e) { updated(e);}
                            public void removeUpdate(DocumentEvent e) { updated(e);}
                            public void changedUpdate(DocumentEvent e) { updated(e);}
                            public void updated(DocumentEvent e) {setDataModified(true);}
                            });

         try
        {
            Database.getTable("EmployeeEducation").setDataEditor(this);
        } catch (SQLException ex)
        {
            ex.printStackTrace();
            log("Gem", "EmployeeEducationEditor.java", Logger.FATAL_ERROR, i18n("Unable to attach editor to the table."), ex);
        }
        // i postaljamo podatke na "nepromenjene"
        setDataModified(false);
    }

  public void userLoggedIn() {

      checkPrivileges();
  }

  /* see if user has all privileges or disable all elements */
  private void checkPrivileges() {

      // if user doesn't have all access disable all fields
      java.util.LinkedList<java.awt.Container> containers = new java.util.LinkedList();
      containers.add(this);

      while(!containers.isEmpty()) {

         java.awt.Container current = containers.getFirst(); // get first element from list
         containers.removeFirst();                           // now remove it from list, it is not needed anymore

         for (java.awt.Component component: current.getComponents()) {

             if (!Integrator._user.getPrivAllAccess())
                 component.setEnabled(false);
             else
                 component.setEnabled(true);
         }
              
      }
      
  }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listCurrentEmployeeEducation = new org.foment.joliage3.newt.SQLListBox();
        comboEducationLevels = new org.foment.joliage3.newt.SQLComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        flg2_EmployeeEducationFacultyTitle = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        flg2_EmployeeEducationDepartment = new javax.swing.JTextArea();
        lblEmployee = new javax.swing.JLabel();
        btnNewEducation = new javax.swing.JButton();
        btnModifyEducation = new javax.swing.JButton();
        btnDeleteEducation = new javax.swing.JButton();
        lblEducationLevel = new javax.swing.JLabel();
        lblFacultyTitle = new javax.swing.JLabel();
        lblDepartment = new javax.swing.JLabel();

        listCurrentEmployeeEducation.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listCurrentEmployeeEducationValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listCurrentEmployeeEducation);

        comboEducationLevels.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboEducationLevelsItemStateChanged(evt);
            }
        });

        flg2_EmployeeEducationFacultyTitle.setColumns(20);
        flg2_EmployeeEducationFacultyTitle.setRows(5);
        flg2_EmployeeEducationFacultyTitle.setName("flg2_EmployeeEducationFacultyTitle"); // NOI18N
        jScrollPane2.setViewportView(flg2_EmployeeEducationFacultyTitle);

        flg2_EmployeeEducationDepartment.setColumns(20);
        flg2_EmployeeEducationDepartment.setRows(5);
        flg2_EmployeeEducationDepartment.setName("flg2_EmployeeEducationDepartment"); // NOI18N
        jScrollPane3.setViewportView(flg2_EmployeeEducationDepartment);

        btnNewEducation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_insert.png"))); // NOI18N
        btnNewEducation.setText(i18n("Add new education"));
        btnNewEducation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewEducationActionPerformed(evt);
            }
        });

        btnModifyEducation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_update.png"))); // NOI18N
        btnModifyEducation.setText(i18n("Modify education"));
        btnModifyEducation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModifyEducationActionPerformed(evt);
            }
        });

        btnDeleteEducation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_reset.png"))); // NOI18N
        btnDeleteEducation.setText(i18n("Delete education"));
        btnDeleteEducation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteEducationActionPerformed(evt);
            }
        });

        lblEducationLevel.setText(i18n("Education level"));

        lblFacultyTitle.setText(i18n("Faculty/School name"));

        lblDepartment.setText(i18n("Department"));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblEmployee, javax.swing.GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblEducationLevel)
                            .addComponent(lblDepartment)
                            .addComponent(lblFacultyTitle))
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
                            .addComponent(comboEducationLevels, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnNewEducation, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnModifyEducation, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDeleteEducation, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(lblEmployee, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(comboEducationLevels, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblEducationLevel))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblFacultyTitle)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblDepartment))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDeleteEducation)
                    .addComponent(btnModifyEducation)
                    .addComponent(btnNewEducation))
                .addContainerGap(102, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void listCurrentEmployeeEducationValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listCurrentEmployeeEducationValueChanged
        // TODO add your handling code here:
        // forsiramo da se prvo izvrsi klik misa.
        listCurrentEmployeeEducation.listener();
        // potom uzimamo selektovanu vrednost iz liste.
        _currentEducation = listCurrentEmployeeEducation.getValue();

        if (_currentEducation != -1 && _currentEmployee != -1)
        {
            // uzimamo sve podatke o izabranoj skoli.
            String query = "SELECT * FROM EmployeeEducation WHERE EmployeeEducationID = " + _currentEducation;

            try
            {
                Connection conn = Database.getConnection();
                ResultSet rs = conn.createStatement().executeQuery(query);
                if (rs.first())
                {
                    flg2_EmployeeEducationFacultyTitle.setText(rs.getString(flg2_EmployeeEducationFacultyTitle.getName().substring(5)));
                    flg2_EmployeeEducationDepartment.setText(rs.getString(flg2_EmployeeEducationDepartment.getName().substring(5)));
                    _educationLevel = rs.getInt("EducationLevelID");
                    comboEducationLevels.setValue(_educationLevel);

                    setDataModified(false);

                }
                rs.close();
                conn.close();
            }
            catch(SQLException e) {e.printStackTrace();}
        }
    }//GEN-LAST:event_listCurrentEmployeeEducationValueChanged

    private void comboEducationLevelsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboEducationLevelsItemStateChanged
        // TODO add your handling code here:
        setDataModified(true);
    }//GEN-LAST:event_comboEducationLevelsItemStateChanged

    private void btnNewEducationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewEducationActionPerformed
        // TODO add your handling code here:
        if (_currentEmployee != -1) {
            String message = i18n("Are you sure you want to add new education for this Employee?");
            String[] options = {i18n("Yes"), i18n("No")};

            int option = JOptionPane.showOptionDialog(this, message, "Foment Group", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0);

            // ako smo kliknuli na YES, uzimamo podatke iz tekst polja...
            // UBACITI ISPITIVANJE JE L' SU POLJA PRAZNA.
            if (option == JOptionPane.YES_OPTION)
            {
                // prvo uzimamo najveci do tad kljuc...
                try
                {
                    Connection conn = Database.getConnection();
                    ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                            ResultSet.CONCUR_UPDATABLE).executeQuery("SELECT max(EmployeeEducationID) + 1 as InsertID FROM EmployeeEducation");
                    int InsertID = 0;
                    if (rs.first())
                        InsertID = rs.getInt("InsertID");
                    rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                            ResultSet.CONCUR_UPDATABLE).executeQuery("SELECT * FROM EmployeeEducation");
                    // pomeramo se na prazan red, za unos novog osiguranika
                    rs.moveToInsertRow();
                    // i rucno unosimo kljuc, jer on nije sadrzan u gui-ju
                    rs.updateInt("EmployeeEducationID", InsertID);
                    rs.updateInt("EmployeeID", _currentEmployee);

                    // potom, unosimo sadrzaj tekst kontrola.
                    rs.updateString(flg2_EmployeeEducationFacultyTitle.getName().substring(5),
                            flg2_EmployeeEducationFacultyTitle.getText());
                    rs.updateString(flg2_EmployeeEducationDepartment.getName().substring(5),
                            flg2_EmployeeEducationDepartment.getText());
                    rs.updateInt("EducationLevelID", comboEducationLevels.getValue());

                    rs.insertRow();
                    setDataModified(false);
                    listCurrentEmployeeEducation.refresh();

                    rs.close();
                    conn.close();
                } catch(SQLException ex) {
                    log("Gem", "EmployeeEducationEditor.java", Logger.ERROR, i18n("Unable to insert data"), ex);
                    ex.printStackTrace();}
            }

        }
}//GEN-LAST:event_btnNewEducationActionPerformed

    private void btnModifyEducationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModifyEducationActionPerformed
        // TODO add your handling code here:

        String query1 = "SELECT * from EmployeeEducation where EmployeeEducationID = " + _currentEducation;
        try
        {
            Connection conn = Database.getConnection();
            ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE).executeQuery(query1);
            if (rs.first())
            {
                rs.updateString(flg2_EmployeeEducationFacultyTitle.getName().substring(5),
                        flg2_EmployeeEducationFacultyTitle.getText());
                rs.updateString(flg2_EmployeeEducationDepartment.getName().substring(5),
                        flg2_EmployeeEducationDepartment.getText());
                rs.updateInt("EducationLevelID", comboEducationLevels.getValue());
            }
            rs.updateRow();
            rs.close();
            conn.close();
            Database.getTable("EmployeeEducation").reload();
            setDataModified(false);
        } catch (SQLException e) {e.printStackTrace();}
}//GEN-LAST:event_btnModifyEducationActionPerformed

    private void btnDeleteEducationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteEducationActionPerformed
        // TODO add your handling code here:
        // uklanjamo osiguranika.
        String message = i18n("Are you sure you want to delete education for this Employee?");
        String[] options = {i18n("Yes"), i18n("No")};

        int option = jOptionPane.showOptionDialog(this, message, "Foment Group", jOptionPane.YES_NO_OPTION, jOptionPane.QUESTION_MESSAGE, null, options, 0);

        if (option == jOptionPane.YES_OPTION) {
            String query = "DELETE FROM EmployeeEducation WHERE EmployeeEducationID = " +
                    _currentEducation + ";";

            try
            {
                Connection conn = Database.getConnection();
                conn.createStatement().executeUpdate(query);
                conn.close();
                Database.getTable("EmployeeEducation").reload();                
            }
            catch (SQLException ex)
            {
                ex.printStackTrace();
            }
        }
        listCurrentEmployeeEducation.refresh();
        clearGui();
        setDataModified(false);
    }//GEN-LAST:event_btnDeleteEducationActionPerformed

    private void setComponents()
    {
        // postavljamo sadrzaj combopolja
        String query = "SELECT EducationLevelID as keyName, EducationLevelTitle as fieldName from EducationLevel";
        comboEducationLevels.setQuery(query);
        comboEducationLevels.listenTables("EducationLevel");
    }
    public void update() throws SQLException
    {
        lblEmployee.setText(
        "<html>(" + Database.getTable("Employee").getResultSet().getString("EmployeeID") + ") " +
        "<b>" + Database.getTable("Employee").getResultSet().getString("EmployeeSurname") + ", " +
        Database.getTable("Employee").getResultSet().getString("EmployeeFirstName") + "</b>"
        );

        _currentEmployee = Database.getTable("Employee").getResultSet().getInt("EmployeeID");

        String query = "SELECT ee.EmployeeEducationID as keyName, ee.EmployeeEducationFacultyTitle as fieldName FROM EmployeeEducation ee WHERE" +
                " ee.EmployeeID = " + _currentEmployee;
        listCurrentEmployeeEducation.setQuery(query);
        // staviti za listentables...
        listCurrentEmployeeEducation.listenTables("EmployeeEducation");
        clearGui();
    }

    private void clearGui()
    {
        flg2_EmployeeEducationDepartment.setText("");
        flg2_EmployeeEducationFacultyTitle.setText("");
        comboEducationLevels.setValue(0);
    }
    public boolean isDataModified() {
        return _modified;
    }

    public void setDataModified(boolean modified) {
        _modified = modified;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDeleteEducation;
    private javax.swing.JButton btnModifyEducation;
    private javax.swing.JButton btnNewEducation;
    private org.foment.joliage3.newt.SQLComboBox comboEducationLevels;
    private javax.swing.JTextArea flg2_EmployeeEducationDepartment;
    private javax.swing.JTextArea flg2_EmployeeEducationFacultyTitle;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblDepartment;
    private javax.swing.JLabel lblEducationLevel;
    private javax.swing.JLabel lblEmployee;
    private javax.swing.JLabel lblFacultyTitle;
    private org.foment.joliage3.newt.SQLListBox listCurrentEmployeeEducation;
    // End of variables declaration//GEN-END:variables

    private int _currentEmployee = -1;
    private int _currentEducation = -1;
    private int _educationLevel = -1;
    private boolean _modified;
    private JOptionPane jOptionPane;
}
